package com.bao123.email.service.impl;

import com.bao123.email.service.EmailService;
import com.bao123.email.service.VerificationCodeService;
import com.bao123.email.vo.MailVO;
import com.bao123.redis.service.RedisStringService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * 验证码服务类实现类
 * @author lbw
 */
@Service
public class VerificationCodeServiceImpl implements VerificationCodeService {
    private static final int VERIFICATION_CODE_LENGTH = 5;

    @Autowired
    private EmailService emailService;
    @Autowired
    private RedisStringService redisStringService;

    @Value("${spring.mail.username}")
    private String from;

    private static final char[] CHARS = new char[]{'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P',
            'Q','R','S','T','U','V','W','X','Y','Z', 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p',
            'q','r','s','t', 'u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9'};

    @Override
    public void sendVerificationCode(String email) {
        MailVO mailVO = new MailVO();
        mailVO.setFrom(from);
        mailVO.setTo(email);
        mailVO.setSubject("您的验证码");
        String verificationCode = generateVerificationCode();
        String text = "尊敬的用户您好,本次验证码为：" + verificationCode + "请勿将验证码泄露给其他人,该验证码30分钟内有效。";
        mailVO.setText(text);
        emailService.sendMimeMail(mailVO);
        String key = email + ":VerificationCode";
        //将验证码放入redis中，用于用户注册时的验证
        redisStringService.setKey(key, verificationCode, 1800);
    }

    /**
     * 验证码生成
     * @return 验证码
     */
    private static String generateVerificationCode(){
        StringBuilder builder = new StringBuilder();
        for (int i=0; i<VERIFICATION_CODE_LENGTH; i++){
            int index = (int) (Math.random() * 62);
            builder.append(CHARS[index]);
        }
        return builder.toString();
    }

}
